package com.itany.webstock;

import com.alibaba.fastjson.JSON;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket服务端对象
 *
 * ServerEndpoint:注解是一个类层次的注解用于将当前类
 *                标注为服务器端类。
 */
@ServerEndpoint("/talk/{userId}")
public class WebSocketServer {


    private Session session;

    private String userName;

    private Integer userId;


    public static CopyOnWriteArraySet<WebSocketServer> webSocketSet
            = new CopyOnWriteArraySet<WebSocketServer>();


    /**
     * 连接成功时触发
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId){
          this.session=session;
          this.userName="用户"+new Random().nextInt(100);
          this.userId=Integer.parseInt(userId!=null?userId:"0");
          webSocketSet.add(this);

    }

    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(Session session){
        webSocketSet.remove(this);
    }

    /**
     * 发生错误调用时触发
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session,Throwable throwable){
        webSocketSet.remove(this);
    }

    /**
     * 收到客户端信息时触发
     * @param message
     * @param session
     */
    @OnMessage
    public   void onMessage(String message,Session session)throws Exception{
          //向所有人推送此消息
          for(WebSocketServer server:webSocketSet){
              Map<String,Object> map = new HashMap<String,Object>();
              map.put("flag",1);
              map.put("msg",this.userName+":"+message);
              synchronized (server.getSession()){
                  //将字符串信息推送给了session对应的界面
                  server.getSession().getBasicRemote().sendText(JSON.toJSONString(map));
              }
          }
    }


    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}
